package com.hubing.cloud.app.web.util;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DateUtil {

    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /**
     * 获取该时间的 前31天
     *
     * @return
     */
    public static Date getDate(int field, int amount) {
        Calendar calendar = Calendar.getInstance();
        calendar.add(field, amount);
        return calendar.getTime();
    }

    public static String format(Date date) {
        try {
            return sdf.format(date);
        } catch (Exception e) {
            return null;
        }
    }

    public static void main(String[] args) {
        Date yesterday = DateUtil.getDate(Calendar.DAY_OF_WEEK, -1);
        Date week = DateUtil.getDate(Calendar.DAY_OF_WEEK, -7);
        Date month = DateUtil.getDate(Calendar.MONTH, -1);
        Date halfYear = DateUtil.getDate(Calendar.MONTH, -6);
        System.out.println(format(yesterday));
        System.out.println(format(week));
        System.out.println(format(month));
        System.out.println(format(halfYear));
    }
}
